find_package(Git)
if(GIT_FOUND)
  set(USE_GIT 1)
else()
  set(USE_GIT 0)
endif()

if(${USE_GIT} EQUAL 1)
  execute_process(
    COMMAND ${GIT_EXECUTABLE} describe --tags --dirty
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    OUTPUT_VARIABLE GIT_DESCRIBE_VERSION
    RESULT_VARIABLE GIT_DESCRIBE_RESULT
    ERROR_VARIABLE  GIT_DESCRIBE_ERROR
    OUTPUT_STRIP_TRAILING_WHITESPACE
    )
  execute_process(
    COMMAND ${GIT_EXECUTABLE} config --get user.name
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    OUTPUT_VARIABLE GIT_CONFIG_USERNAME
    RESULT_VARIABLE GIT_CONFIG_RESULT
    ERROR_VARIABLE  GIT_CONFIG_ERROR
    OUTPUT_STRIP_TRAILING_WHITESPACE
    )
else()
  set(GIT_DESCRIBE_RESULT -1)
  set(GIT_CONFIG_RESULT -1)
endif()

#
# Deal with version first
#
if(GIT_DESCRIBE_RESULT EQUAL 0)
  file(WRITE ${CMAKE_BINARY_DIR}/source/VERSION "${GIT_DESCRIBE_VERSION}")
else()
  file(READ ${CMAKE_SOURCE_DIR}/VERSION GIT_DESCRIBE_VERSION)
endif()

string(REGEX REPLACE "v([0-9]*)\\.([0-9]*)(-(.*))?"
  "\\1;\\2;\\4" VLIST "${GIT_DESCRIBE_VERSION}")
#message(INFO " vlist ${VLIST}")

list(GET VLIST 0 VERSION_MAJOR)
list(GET VLIST 1 VERSION_MINOR)
list(LENGTH VLIST VLISTLEN)
if(VLISTLEN EQUAL 3)
  list(GET VLIST 2 VERSION_EXTRA)
endif()
set(VERSION "${VERSION_MAJOR}.${VERSION_MINOR}-${VERSION_EXTRA}")

# 
# Deal with username
#
string(LENGTH "${GIT_CONFIG_USERNAME}" GIT_CONFIG_USERNAME_LENGTH)
#message(INFO "uname <${GIT_CONFIG_USERNAME}>")
#message(INFO "length ${GIT_CONFIG_USERNAME_LENGTH}")
if(GIT_CONFIG_USERNAME_LENGTH EQUAL 0)
  set(GIT_CONFIG_RESULT -1)
endif()

if(GIT_CONFIG_RESULT EQUAL -1)
  if(WIN32)
    set(PKG_USERNAME "$ENV{USERNAME}")
  else()
    set(PKG_USERNAME "$ENV{USER}")
  endif()
else()
  set(PKG_USERNAME "${GIT_CONFIG_USERNAME}")
endif()
#message(INFO "user ${PKG_USERNAME}")